package com.bafenyi.zh.bafenyilib.request;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;


import com.bafenyi.zh.bafenyilib.config.BFYConfig;
import com.bafenyi.zh.bafenyilib.request.Bean.BaseEntity;
import com.bafenyi.zh.bafenyilib.request.Bean.MoreAppBean;
import com.bafenyi.zh.bafenyilib.request.http_config.RxService;
import com.bafenyi.zh.bafenyilib.util.MacMethod;
import com.bafenyi.zh.bafenyilib.util.PreferenceUtil;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.crypto.Mac;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static android.content.Context.TELEPHONY_SERVICE;

public class BFYRequest {

    /**
     * 获取服务器时间错
     * @param resultListener 回调接口
     * */
    public static void getTimeStamp(BFYRequestListener.TimeStampResult resultListener) {
        // 获取时间戳
        RxService.createApi(APIFunction.class)
                .getTimeStampApi()
                .timeout(5 , TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<HashMap<String, String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HashMap<String, String> stringStringHashMap) {
                        resultListener.onResult(true, stringStringHashMap.get("data"));
                    }

                    @Override
                    public void onError(Throwable e) {
                        resultListener.onResult(false, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    /**
     * 上报统计
     * @param context 上下文
     * @param timeStamp 服务器时间戳
     * @param reportStatisticalResult 回调接口
     * */
    @SuppressLint("HardwareIds")
    public static void reportStatistical(Context context, String timeStamp , BFYRequestListener.ReportStatisticalResult reportStatisticalResult) {
        String deviceId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String IMEI = "";
        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        try {
            IMEI = TelephonyMgr.getDeviceId();
        }catch (java.lang.RuntimeException error) { }
        String appId = BFYConfig.getStaticticalAppid();
        String appSecret = BFYConfig.getStatisticalAppSecret();
        String appVersion = BFYConfig.getAppVersion();
        String phoneModel = Build.MODEL;
        String systemVersion = Build.VERSION.RELEASE;
        String appVersionCode = BFYConfig.getAppVersionCode();
        String appMacID = MacMethod.getMac(context);
        String oaid = BFYConfig.getOaid();
        HashMap<String , String> sign_map = new HashMap<String , String>();

        sign_map.put("appId" , appId);
        sign_map.put("appSecret" , appSecret);
        sign_map.put("appVersion" , appVersion);
        sign_map.put("deviceId" , deviceId);
        sign_map.put("phoneModel" , phoneModel);
        sign_map.put("systemVersion" , systemVersion);
        sign_map.put("timeStamp" , timeStamp);
        sign_map.put("IMEI" , IMEI);
        sign_map.put("appVersionCode" , appVersionCode);
        sign_map.put("MacId" ,appMacID );
        sign_map.put("oaid" ,oaid );
        String sign_md5 = getSign(sign_map);

        HashMap<String , String> params = new HashMap<String, String>();

        params.put("sign" , sign_md5);
        params.put("appId" , appId);
        params.put("appVersion" , appVersion);
        params.put("deviceId" , deviceId);
        params.put("phoneModel" , phoneModel);
        params.put("systemVersion" , systemVersion);
        params.put("timeStamp" , timeStamp);
        params.put("IMEI" , IMEI);
        params.put("appVersionCode",appVersionCode);
        params.put("MacId",appMacID);
        params.put("oaid" ,oaid );
        RxService.createApi(APIFunction.class)
                .reportDataInfo(params)
                .subscribeOn(Schedulers.io())
                .timeout(5 , TimeUnit.SECONDS)
                .subscribe(new Observer<HashMap<String, String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(@NotNull HashMap<String, String> stringStringHashMap) {
                        if (stringStringHashMap.get("code") != null && Objects.equals(stringStringHashMap.get("code"), "0")) {
                            if (stringStringHashMap.get("data") != null) {
                                PreferenceUtil.put("isAudit" , Objects.equals(stringStringHashMap.get("data"), "true"));
                            }
                        }else {
                            reportStatisticalResult.onResult(false);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        reportStatisticalResult.onError();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取配置参数
     * @param timeStamp 服务器时间戳
     * @param lastUpdateTime 最后修改时间
     * @param getParamsResult 回调接口
     * */
    public static void getParams(String timeStamp , String lastUpdateTime , BFYRequestListener.GetParamsResult getParamsResult){
        if (PreferenceUtil.getInt("record_code" , 0) != Integer.parseInt(BFYConfig.getAppVersionCode())) {
            lastUpdateTime = "";
        }
        String appId = BFYConfig.getStaticticalAppid();
        String appSecret = BFYConfig.getStatisticalAppSecret();
        HashMap<String , String> sign_map = new HashMap<String , String>();
        sign_map.put("appId" , appId);
        sign_map.put("appSecret" , appSecret);
        sign_map.put("timeStamp" , timeStamp);

        sign_map.put("lastUpdateTime" , lastUpdateTime);

        String sign_md5 = getSign(sign_map);
        HashMap<String , String> params = new HashMap<String, String>();
        params.put("sign" , sign_md5);
        params.put("appId" , appId);
        params.put("timeStamp" , timeStamp);
        params.put("lastUpdateTime" , lastUpdateTime);

        RxService.createApi(APIFunction.class)
                .getParams(params)
                .subscribeOn(Schedulers.io())
                .timeout(5 , TimeUnit.SECONDS)
                .subscribe(new Observer<HashMap<String, Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HashMap<String, Object> stringStringHashMap) {
                        if (stringStringHashMap.get("msg").equals("success")) {
                            PreferenceUtil.put("params" , new Gson().toJson(stringStringHashMap.get("data")));
                            PreferenceUtil.put("record_code" , Integer.parseInt(BFYConfig.getAppVersionCode()));
                        }
                        getParamsResult.onResult(true);
                    }
                    @Override
                    public void onError(Throwable e) {
                        getParamsResult.onResult(false);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取moreapp pic
     * @param resultListener 回调接口
     * */
    public static void getMoreAppPic(BFYRequestListener.getMoreAppPicResult resultListener) {
        HashMap<String , String> sign_map = new HashMap<String , String>();
        sign_map.put("language" , "cn");
        sign_map.put("system","none");
        sign_map.put("x-oss-process","image/resize,w_300");
        // 获取时间戳
        RxService.createApi(APIFunction.class)
                .getMoreAppPic(sign_map)
                .subscribeOn(Schedulers.io())
                .timeout(5 , TimeUnit.SECONDS)
                .subscribe(new Observer<BaseEntity<ArrayList<MoreAppBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseEntity<ArrayList<MoreAppBean>> arrayListBaseEntity) {
                        ArrayList<String> arrayList = new ArrayList<>();
                        if(null != arrayListBaseEntity.getData()) {
                            for (int i = 0; i < arrayListBaseEntity.getData().size() - 1; i++) {
                                arrayList.add(arrayListBaseEntity.getData().get(i).getPicUrl());
                            }
                            if (arrayList.size() > 0) {
                                BFYConfig.setMoreAppPics(arrayList);
                            }
                            resultListener.onResult(true , arrayList);
                        }else {
                            resultListener.onResult(false,arrayList);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                resultListener.onResult(false,new ArrayList<>());
                            }
                        });
                    }
                    @Override
                    public void onComplete() {

                    }
                });
    }
    /**
     * 生成sign并进行md5加密
     * @param sign_map map
     * */
    public static String getSign(@NotNull HashMap<String , String> sign_map) {
        //保存key值的数组
        ArrayList<String> sign_keys = new ArrayList<String>();
        //遍历所有key值保存到数组
        for (Map.Entry<String , String> me : sign_map.entrySet()) {
            sign_keys.add(me.getKey().toLowerCase());
        }
        //key值数组排序
        Collections.sort(sign_keys);
        //返回结果字符串
        String result_str = "";
        //遍历排序后的数组
        for (String key : sign_keys) {
            //遍历map
            for (Map.Entry<String , String> me : sign_map.entrySet()) {
                //找到与排序后的数组里的key对应的may并判断此map没有写入结果字符串
                if (key.equals(me.getKey().toLowerCase()) && !result_str.contains(key)) {
                    //添加到结果字符串
                    result_str = result_str + me.getKey() + "=" + me.getValue() + "&";
                }
            }
        }
        //移除最后一位"&"
        result_str = result_str.substring(0 , result_str.length() - 1);
        //加密并返回
        return md5(result_str);
    }
    /**
     * md5加密
     * @param string 需要加密的字符串
     */
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


}
